<template>
  <div class="excel-container">
    <div class="app-container">
      <el-card>
        <!-- 使用上传Excel组件 -->
        <upload-excel
          :before-upload="handleBeforeUpload"
          :on-success="handleOnSuccess"
        />
      </el-card>
    </div>
  </div>
</template>

<script>
import { addsEmployeesApi } from "@/api/employees";
import { getJsDateFromExcel } from "excel-date-to-js";
import dayjs from "dayjs";
export default {
  name: "ViewsExcel",
  data() {
    return {};
  },
  methods: {
    //上传前的校验
    handleBeforeUpload(file) {
      // file:选择、拖拽的excel文件对象
      const isMt5M = file.size / 1024 / 1024 < 5;
      // 可以校验文件大小，通过了返回true，否则返回false

      if (isMt5M) {
        // 并且只有在返回true的条件下才会触发上传成功
        return true;
      }

      this.$message.warning("文件大小不超过5M");
      return false;
    },
    // 上传成功
    async handleOnSuccess({ header, results }) {
      const userRelations = {
        入职日期: "timeOfEntry",
        手机号: "mobile",
        姓名: "username",
        转正日期: "correctionTime",
        工号: "workNumber",
      };
      // 转换 results 数组，把中文键转为英文键
      //  results 数组，得到新数组
      const employeesList = results.map((item) => {
        const obj = {};
        Object.keys(item).forEach((key) => {
          const enkey = userRelations[key];
          // 给item添加英文key并赋值
          // 如果当前英文key是 timeOfEntry或correctionTime.
          // 需要对Excel时间戳做转换
          if (enkey === "timeOfEntry" || enkey === "correctionTime") {
            obj[enkey] = dayjs(getJsDateFromExcel(item[key])).format(
              "YYYY-MM-DD"
            );
          } else {
            obj[enkey] = item[key];
          }
        });
        return obj;
      });
      // 批量添加
      await addsEmployeesApi(employeesList);
      this.$message.success("批量填充成功");
      // 跳转到上一页
      this.$router.back();
    },
  },
};
</script>

<style>
</style>